from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.http import FileResponse
import time
import os

# 局部禁用csrf
from django.views.decorators.csrf import csrf_exempt

def index(request):
    return HttpResponse("request api sucessfully!")

def sleep(request,sleep_time):
    time.sleep(sleep_time)
    return HttpResponse("sleep_time is %s secs" % sleep_time)

def upload_file(request):
    template = loader.get_template('apis/index.html')
    context = {}
    return HttpResponse(template.render(context, request))

@csrf_exempt
def upload_file_test(request):
    # return HttpResponse('upload file testting')

    # set upload dir
    apis_dir = os.path.join(os.getcwd(), "apis")
    upload_dir = os.path.join(apis_dir, "uploadfiles")
    # return HttpResponse('upload file dir is %s' % upload_dir)

    if request.method == "POST":    # 请求方法为POST时，进行处理
        myFile =request.FILES.get("myfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        if not myFile:
            return HttpResponse("no files for upload!")

        destination = open(os.path.join(upload_dir, myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作

        for chunk in myFile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()
        return HttpResponse("upload over!")

def download(request):
    # return HttpResponse('download!')
    template = loader.get_template('apis/download.html')
    context = {}
    return HttpResponse(template.render(context, request))

def downloadFile(request):
    # return HttpResponse('downloadFile')

    apis_dir = os.path.join(os.getcwd(), "apis")
    download_dir = os.path.join(apis_dir, "downloadfiles")
    file = os.path.join(download_dir,'1.jpg')

    # file=open('/home/amarsoft/download/example.tar.gz','rb')
    file=open(file,'rb')
    response =FileResponse(file)
    response['Content-Type']='application/octet-stream'
    response['Content-Disposition']='attachment;filename="1.jpg"'
    return response